﻿using ApplicationCore.Interfaces;
using System.Threading.Tasks;
using ApplicationCore.Entities;
using System.Linq;
using System.Linq.Expressions;
using Web.ViewModels;
using System.Collections.Generic;
using ApplicationCore.Specifications;
using System;
using Infrastructure.Data;

namespace Web.Services
{
	public class ChatMsgService : IChatMsgService
	{
		private readonly IChatMsgRepository  _repo;
		private readonly IRoomRepository _roomRepo;
		private readonly ZBContext _zbContext;

		public ChatMsgService(IChatMsgRepository repo, IRoomRepository  roomRepo, ZBContext zbContext)
		{
			this._repo = repo;
			_roomRepo = roomRepo;
			_zbContext =  zbContext;

		}
		public Task<List<ChatMsgViewModel>> GetItemsByRoomId(int id, DateTime day)
		{
			var list = _repo.ListAll( ).Where(s=>
			s.RoomId==id && 
			s.CreateAt>=new DateTime(day.Year,day.Month,day.Day)&&
			s.CreateAt<=DateTime.Now
			
			
			);
			if (!list.Any()) return Task.FromResult<List<ChatMsgViewModel>>(new List<ChatMsgViewModel>());
			var re = new List<ChatMsgViewModel>();
			list.ToList().ForEach(s => {

				re.Add(new ChatMsgViewModel(s));
			});

			return Task.FromResult(re);

		}

		/// <summary>
		/// 根据房间号获取 某天的消息
		/// </summary>
		/// <param name="no"></param>
		/// <param name="day"></param>
		/// <returns></returns>
		public Task<List<ChatMsgViewModel>> GetItemsByRoomNo(string no,DateTime day)
		{
			///获取room实体
		 	var room=_roomRepo.ListAll().SingleOrDefault(s=>s.RoomNo==no);
			if (room == null)
			{
				throw new  ArgumentNullException("找不到房间");
			}
			 
			return GetItemsByRoomId(room.Id,day);
		}

		public Task<ChatMsgViewModel> SendChatMsg(string message, int roomId,string fromUserId, string toUserId)
		{
			var room = _roomRepo.GetById(roomId);
			var input = new ChatMsg
			{
				Content = message,
				RoomId = roomId,
				UserIdFrom = fromUserId,
				UserIdTo = toUserId,
				CreateAt = DateTime.Now,
				ChatMsgState = room.AMA== AutomaticMessageAudit.Yes? ChatMsgState.Pass: ChatMsgState.WaitforAudit,
				 ChatMsgType= string.IsNullOrWhiteSpace(toUserId)? ChatMsgType.Normal: ChatMsgType.PrivateChat,
				  
			};

			var entity = _repo.Add(input);
			var re = new ChatMsgViewModel(entity);

			return Task.FromResult(re);

		}

	}
}
